﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Communications;

using CharityGamesOnline.Modules.Charity;
using CharityGamesOnline.Modules.Game;
using CharityGamesOnline.Modules.Common;

namespace CharityGamesOnline.Modules.Event
{
    public partial class EventDetail : CGOBase
    {
        protected int eventID = 0;

        public int EventID
        {
            get
            {
                if (eventID==0)
                {
                    if ((Request.QueryString["EventID"] != null))
                    {
                        eventID = Int32.Parse(Request.QueryString["EventID"]);
                    }
                }
                return eventID;
            }            
        }

        public int CharityDetailTabID
        {
            get
            {
                if (!Null.IsNull(Settings["CharityDetailTabID"]) && Int32.Parse(Settings["CharityDetailTabID"].ToString())>0)
                {
                    return Int32.Parse(Settings["CharityDetailTabID"].ToString());
                }
                else
                    return 0;
            }
        }

        public int EventDetailTabID
        {
            get
            {
                if (!Null.IsNull(Settings["EventDetailTabID"]) && Int32.Parse(Settings["EventDetailTabID"].ToString())>0)
                {
                    return Int32.Parse(Settings["EventDetailTabID"].ToString());
                }
                else
                    return TabId;
            }
        }

        public int ArchiveDetailTabID
        {
            get
            {
                if (!Null.IsNull(Settings["ArchiveDetailTabID"]))
                {
                    return Int32.Parse(Settings["ArchiveDetailTabID"].ToString());
                }
                else
                    return TabId;
            }
        }

        public int GameDetailTabID
        {
            get
            {
                if (!Null.IsNull(Settings["GameDetailTabID"]))
                {
                    return Int32.Parse(Settings["GameDetailTabID"].ToString());
                }
                else
                    return 0;
            }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            // If this is the first visit to the page, bind the role data to the datalist 
            if (Page.IsPostBack == false)
            {
                BindData();
            }
        }

        protected void btnPlay_Click(object sender, ImageClickEventArgs e)
        {
            if (GameDetailTabID != 0)
            {
                Response.Redirect(Globals.NavigateURL(GameDetailTabID, string.Empty, "EventID=" + ((ImageButton)sender).CommandArgument));
            }
        }

        protected void btnTry_Click(object sender, ImageClickEventArgs e)
        {
            if (GameDetailTabID != 0)
            {
                Response.Redirect(Globals.NavigateURL(GameDetailTabID, string.Empty, "TryGame=True", "EventID=" + ((ImageButton)sender).CommandArgument));
            }
        }

        #region Public Function

        public void BindData(int intEventID)
        {
            eventID = intEventID;
            BindData();
        }

        #endregion

        #region Private Function

        private void BindData()
        {
            lbMessage.Visible = false;
            pnlEventDetail.Visible = true;

            if (EventID > 0)
            {
                // get content 
                EventController ctrlEvent = new EventController();
                EventInfo objEvent = ctrlEvent.GetEvent(PortalId, EventID);
                int targetTabID = TabId;

                if (objEvent != null)
                {
                    //if event is archived
                    if (objEvent.DateEnd < DateTime.Now)
                    {
                        targetTabID = ArchiveDetailTabID;
                    }
                    else
                    {
                        targetTabID = EventDetailTabID;
                    }

                    if (TabId == targetTabID)
                    {
                        BindEvent(objEvent);
                    }
                    else
                    {
                        Response.Redirect(Globals.NavigateURL(targetTabID, string.Empty, "EventID=" + EventID));  
                    }
                    
                }
                else
                {
                    lbMessage.Visible = true;
                    pnlEventDetail.Visible = false;
                    lbMessage.Text = string.Format(Localization.GetString("errEventNotExist", LocalResourceFile), EventID);
                }
            }
            else
            {
                lbMessage.Visible = true;
                pnlEventDetail.Visible = false;
                lbMessage.Text = Localization.GetString("errEventIDInvalid", LocalResourceFile); 
            }
        }

        private void BindEvent(EventInfo e)
        {
            lbEventName.Text = e.Name;
            litDescription.Text = Server.HtmlDecode(e.Description);
            imgLogo.Visible = false;
            if (e.ImageDisplay && !string.IsNullOrEmpty(e.ImageURL))
            {
                imgLogo.Visible = false;
                imgLogo.ImageUrl = GetIconUrl(e, "ImageURL");
                imgLogo.Width = e.ImageWidth;
                imgLogo.Height = e.ImageHeight;
            }

            lbBeginDate.Text = e.DateBegin.Date.ToShortDateString();
            lbEndDate.Text = e.DateEnd.Date.ToShortDateString();
            btnPlay.CommandArgument = e.EventID.ToString();
            btnTry.CommandName = "TRY";
            btnTry.CommandArgument = e.EventID.ToString();

            #region Bind Charity Info

            CharityController ctrlCharity = new CharityController();
            List<CharityInfo> lstCharity = ctrlCharity.GetCharities(PortalId, EventID);

            lbCharityName.Visible = false;
            lnkCharity.Visible = false;

            if (lstCharity.Count != 0)
            {
                lnkCharity.Text = lstCharity[0].Name;
                lbCharityName.Text = lstCharity[0].Name;

                if (CharityDetailTabID > 0)
                {
                    lnkCharity.NavigateUrl = Globals.NavigateURL(CharityDetailTabID, string.Empty, "CharityID=" + lstCharity[0].CharityID);
                    lnkCharity.Visible = true;
                }
                else
                {
                    lbCharityName.Visible = true;                    
                }
            }

            #endregion

            #region Bind Game Info
            GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
            int intGameTotal = ctrlEnroll.GetPlayedCount(PortalId, EventID, 0, 0, 0);
            int intGameEnroll = ctrlEnroll.GetPlayedCount(PortalId, EventID, 0, 0, (int)GameEnrollmentInfo.STATUS.ENROLLED);
            int intGamePlayed = intGameTotal - intGameEnroll;
            
            if (e.MaxEnrollment == 0)
            {
                lbGameAvailable.Text = Localization.GetString("unlimitedGameRemain", LocalResourceFile);
                lbGameCount.Text = Localization.GetString("unlimitedGameRemain", LocalResourceFile);
            }
            else
            {
                lbGameAvailable.Text = (e.MaxEnrollment - intGamePlayed).ToString();
                lbGameCount.Text = e.MaxEnrollment.ToString();
            }
            decimal totalAmount = ctrlEnroll.GetMoneyCount(PortalId, EventID);
            decimal unpaidAmount = ctrlEnroll.GetMoneyCount(PortalId, EventID, 0, 0, (int)GameEnrollmentInfo.STATUS.ENROLLED);
            decimal donateAmount = totalAmount - unpaidAmount;

            lblDonationMoney.Text = string.Format(Localization.GetString("doationFormat", LocalResourceFile), donateAmount); 
            
            #endregion

            #region Check if game available
            btnPlay.Visible = true;
            btnPlay.Enabled = true;
            btnTry.Visible = true;
            btnTry.Enabled = true;
            btnPlay.ImageUrl = "images/playnow.png";

            if (DateTime.Now > e.DateEnd)
            {
                btnTry.Visible = false;
                btnPlay.Enabled = false;
                btnPlay.ImageUrl = "images/expired.png";
            }
            else if (DateTime.Now < e.DateBegin)
            {
                btnPlay.Enabled = false;
                btnPlay.ImageUrl = "images/startsoon.png";
            }
            else if (!IsEnrolled(e))
            {
                if (!e.Signups)
                {
                    btnPlay.Enabled = false;
                    btnPlay.ImageUrl = "images/locked.png";
                }                
                else if (e.MaxEnrollment != 0 && intGamePlayed >= e.MaxEnrollment)
                {
                    btnPlay.Enabled = false;
                    btnPlay.ImageUrl = "images/outnumbered.png";
                }                
            }
            #endregion
        }

        private bool IsEnrolled(EventInfo e)
        {
            bool enrolled = false;
            GameController ctrlGame = new GameController();
            GameEnrollmentController ctrlEnroll = new GameEnrollmentController();
            List<GameInfo> lstGame = ctrlGame.GetGames(PortalId, e.EventID);
            if (lstGame.Count > 0)
            {
                int gameID = lstGame[0].GameID;
                int enrollID = ctrlEnroll.GetUncompletedEnrollID(PortalId, e.EventID, gameID, UserId);
                if (enrollID != 0)
                {
                    enrolled = true;
                }                
            }
            return enrolled;
        }

        #endregion        
    }
}